﻿#ifndef AUDIOCONTROLER_H
#define AUDIOCONTROLER_H
#include "Aconfig.h"

#include <QObject>
#include <QDebug>
#include <QFile>
#include <QTimer>
#include <queue>


#include <QAudioFormat>
#include <QAudioInput>
#include <QAudioOutput>
#include <QMediaPlayer>
#include "../resources/snowboy_resources/include/snowboy-detect.h"

#include "../resources/sherpaNcnn_resources/include/c-api.h"
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>
#include <fstream>

#include "../resources/sherpaOnnx_resources/include/c-api.h"
#include <QDir>


using namespace std;



#include <QThread>


struct SpeechTask {
    QString content;  // 语音内容
    int priority;     // 播报优先级

    bool operator<(const SpeechTask& other) const {
        return priority < other.priority; // 优先级较高的排在前面
    }
};


class AudioControler : public QObject
{
    Q_OBJECT
public:
    explicit AudioControler(QObject *parent = 0);

    bool audioInit();
    bool snowboyInit();

    bool getAudioControlerInit_state();

    bool playAudio(QString& audioPath);

    bool sherpancnnInit();

    void start_snowboyInterrupt();
    void stop_snowboyInterrupt();

    void sherpaNcnnRecognition();
    bool readCommandsFromFile();
    double calculateSimilarity(const string& userCommand, const string& command);
    string matchCommand(const string& userCommand);
    void processCommand(const string& command_matched);

    bool sherpaonnxInit();

    void generateAudio(const QString &text, const QString &outputFile);


signals:
    void initialized_sig();

public slots:
    bool initialize();
    void snowboyInterrupt();

    void getSpeechTeskFromController_slot(QString str,int priority);

    void startNextSpeech_slot(); // 播放下一个语音任务


private:
    bool initialized_state = false;

private:
    bool audioDeviceBusy = false;

private:
    QAudioInput* audioInput;
    QAudioOutput* audioOutput;
    QMediaPlayer* mediaPlayer;
    QIODevice* audioDevice;

    snowboy::SnowboyDetect*snowboyDetect;

    QByteArray audioBuffer;
    SherpaNcnnRecognizer* recognizer;
    SherpaNcnnStream* stream;
    vector<string> commands;

    SherpaOnnxOfflineTts *tts;


private:
    std::priority_queue<SpeechTask> speechQueue; // 语音任务的优先级队列
    QTimer startNextSpeechTimer; // 定时器控制任务播放
};

#endif // AUDIOCONTROLER_H
